package com.sendpo.zjx.sendpo.activity;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.sendpo.zjx.sendpo.BuildConfig;
import com.sendpo.zjx.sendpo.R;
import com.sendpo.zjx.sendpo.net.HttpCode;
import com.sendpo.zjx.sendpo.net.HttpUrl;
import com.sendpo.zjx.sendpo.services.AmapLocationService;
import com.sendpo.zjx.sendpo.table.User;
import com.sendpo.zjx.sendpo.utils.Tools;
import com.sendpo.zjx.sendpo.utils.Xutils;
import com.wefika.flowlayout.FlowLayout;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.shaohui.bottomdialog.BottomDialog;

/**
 * Created by 朱俊鑫 on 2018
 */

public class MerchantFriendCircleSubmitActivity extends AppCompatActivity implements AMapLocationListener {

    @BindView(R.id.backbt)
    RelativeLayout backbt;
    @BindView(R.id.head)
    RelativeLayout head;
    @BindView(R.id.submit_bt)
    Button submitBt;
    @BindView(R.id.bottom)
    RelativeLayout bottom;

    @BindView(R.id.flowlayout)
    FlowLayout flowlayout;
    @BindView(R.id.spinner)
    Spinner spinner;
    @BindView(R.id.addtitle_bt)
    RelativeLayout addtitleBt;
    @BindView(R.id.addtag)
    HorizontalScrollView addtag;
    @BindView(R.id.openupload_all)
    LinearLayout openuploadAll;
    @BindView(R.id.hsv)
    HorizontalScrollView hsv;
    @BindView(R.id.openupload_iv)
    ImageView openuploadIv;
    public final int REQUEST_IMAGECOUNT = 1031;
    public final int REQUEST_CAMERA = 104;
    public final int REQUEST_CROP = 105;
    BottomDialog bottomDialog;
    public List<String> fileList = new ArrayList<>();
    File temp_cmera = null;
    @BindView(R.id.title)
    EditText title;
    @BindView(R.id.edit_text)
    EditText editText;

    private Dialog loadingdialog, tagdialog;

    public AmapLocationService amapLocationService;
    public double userLongitude = 0;
    public double userLatitude = 0;
    public String userProvince = "";
    public String userCity = "";
    public String userArea = "";
    public String userAddress = "";
    private List<String> ars=new ArrayList<>();      ;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_myselffabulist_edit);
        ButterKnife.bind(this);
        Tools.initStatus(this, R.color.black);

        initComponent();
    }

    private void initComponent() {
        loadingdialog = new Dialog(this);
        loadingdialog.setContentView(R.layout.dialog_loading);
        loadingdialog.setCanceledOnTouchOutside(false);
        loadingdialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        bottomDialog = BottomDialog.create(getSupportFragmentManager());
        bottomDialog.setViewListener(new BottomDialog.ViewListener() {
            @Override
            public void bindView(View v) {
                v.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View camera = v.findViewById(R.id.camera);
                camera.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        temp_cmera = new File(getExternalCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString().substring(0, 10) + ".jpg");
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        intent.putExtra("return-data", true);
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            Uri contentUri = FileProvider.getUriForFile(MerchantFriendCircleSubmitActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", temp_cmera);
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, contentUri);
                        } else {
                            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                        }
                        startActivityForResult(intent, REQUEST_CAMERA);
                        bottomDialog.dismiss();
                    }
                });
                View exit = v.findViewById(R.id.exit);
                exit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        bottomDialog.dismiss();
                    }
                });
                View imgcontent = v.findViewById(R.id.imgcontent);
                imgcontent.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
                        intent.setType("image/*");
                        intent.putExtra("return-data", true);
                        startActivityForResult(intent, REQUEST_IMAGECOUNT);
                        bottomDialog.dismiss();
                    }
                });
            }
        });
        bottomDialog.setLayoutRes(R.layout.dialog_uploadimg);
        bottomDialog.setDimAmount(0.5f);
        bottomDialog.setCancelOutside(true);
        bottomDialog.setTag("BottomDialog");
        amapLocationService = new AmapLocationService(this);
        amapLocationService.setmLocationOption(getDefaultAmapLocationOptions());
        amapLocationService.registerListener(this);
        amapLocationService.start();
    }

    @OnClick(value = {R.id.backbt, R.id.openupload_iv,R.id.addtitle_bt,R.id.submit_bt})
    public void onMyClick(View view) {
        switch (view.getId()) {
            case R.id.addtitle_bt:
                startActivityForResult(new Intent(this, MyselfFabuListAddTitleActivity.class), 106);
                break;
            case R.id.backbt:
                finish();
                break;
            case R.id.openupload_iv:
                if (fileList.size() >= 4) {
                    Toast.makeText(this.getApplicationContext(), "已有4张图片", Toast.LENGTH_SHORT).show();
                    return;
                }
                bottomDialog.show();
                break;
            case R.id.submit_bt:
                if (TextUtils.isEmpty(this.title.getText().toString().trim()))
                {
                    Toast.makeText(getApplicationContext(), "标题不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (TextUtils.isEmpty(this.editText.getText().toString().trim()))
                {
                    Toast.makeText(getApplicationContext(), "内容不能为空", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (fileList.size() == 0) {
                    Toast.makeText(this.getApplicationContext(), "图片至少一张", Toast.LENGTH_SHORT).show();
                    return;
                }
                String officatg="";
              if(ars!=null){
                  for(String s:ars){
                      officatg=officatg+ ",";
                  }
              }
                submit(editText.getText().toString().trim(),title.getText().toString().trim(),
                        officatg,spinner.getSelectedItemPosition()+"");
                break;
        }
    }

    public AMapLocationClientOption getDefaultAmapLocationOptions() {
        AMapLocationClientOption mLocationOption = null;
        if (mLocationOption == null) {
            mLocationOption = new AMapLocationClientOption();
            //设置定位模式为AMapLocationMode.Hight_Accuracy，高精度模式。
            mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
            mLocationOption.setLocationCacheEnable(true);
            mLocationOption.setOnceLocation(true);
            mLocationOption.setOnceLocationLatest(false);
            //设置是否返回地址信息（默认返回地址信息）
            mLocationOption.setNeedAddress(true);
            //设置是否强制刷新WIFI，默认为true，强制刷新。
            mLocationOption.setWifiScan(true);
            mLocationOption.setInterval(1000);
            //单位是毫秒，默认30000毫秒，建议超时时间不要低于8000毫秒。
            mLocationOption.setHttpTimeOut(20000);
        }
        return mLocationOption;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (fileList != null && fileList.size() != 0) {
            for (String file : fileList) {
                File file1 = new File(file);
                file1.delete();
            }
        }
    }


    @Override
    public void onLocationChanged(AMapLocation aMapLocation) {
        if (amapLocationService == null || aMapLocation == null) {
            Toast.makeText(getApplicationContext(), "定位失败，请检查网络和手机权限或者是否打开GPS", Toast.LENGTH_SHORT).show();
            return;
        }
        userLongitude = aMapLocation.getLongitude();
        userLatitude = aMapLocation.getLatitude();
        userProvince = aMapLocation.getProvince();
        userCity = aMapLocation.getCity();
        userArea = aMapLocation.getDistrict();
        int index = aMapLocation.getAddress().lastIndexOf(userProvince + userCity + userArea);
        userAddress = aMapLocation.getAddress().substring(index + (userProvince + userCity + userArea).length(), aMapLocation.getAddress().length());
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_IMAGECOUNT:
                Uri datauri = data.getData();
                final File finalFile1 = new File(getExternalCacheDir().getAbsolutePath() + "/" + UUID.randomUUID().toString().substring(0, 10) + ".png");
                ;
                Glide.with(this)
                        .load(datauri)
                        .asBitmap()
                        .override(500, 500)
                        .placeholder(getResources().getColor(R.color.default_lightgray))
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                try {
                                    Bitmap bitmap = null;
                                    if (resource.getHeight() < 500) {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 1, resource.getHeight() / 1);
                                    } else if (resource.getHeight() < 1000) {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 2, resource.getHeight() / 2);
                                    } else {
                                        bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 3, resource.getHeight() / 3);
                                    }
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(finalFile1));
                                    fileList.add(finalFile1.getPath());
                                    final View imgview = View.inflate(MerchantFriendCircleSubmitActivity.this, R.layout.layout_uploadimg_layout, null);
                                    ImageView imgview_iv = imgview.findViewById(R.id.image);
                                    imgview_iv.setImageBitmap(BitmapFactory.decodeFile(finalFile1.getPath()));
                                    View imgview__delte = imgview.findViewById(R.id.delete_iv);
                                    imgview__delte.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            openuploadAll.removeView(imgview);
                                            fileList.remove(finalFile1.getPath());
                                        }
                                    });
                                    openuploadAll.addView(imgview);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;

            case REQUEST_CAMERA:
                Intent bgcamera = new Intent("com.android.camera.action.CROP");
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    bgcamera.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    Uri contentUri = FileProvider.getUriForFile(MerchantFriendCircleSubmitActivity.this, BuildConfig.APPLICATION_ID + ".fileProvider", temp_cmera);
                    bgcamera.setDataAndType(contentUri, "image/*");
                } else {
                    bgcamera.setDataAndType(Uri.fromFile(temp_cmera), "image/*");
                }
                bgcamera.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(temp_cmera));
                bgcamera.putExtra("return-data", false);
                bgcamera.putExtra("scale", true);
                bgcamera.putExtra("outputFormat", Bitmap.CompressFormat.PNG);
                bgcamera.putExtra("noFaceDetection", true);
                //     bgcamera.putExtra("aspectX",son1);
                //     bgcamera.putExtra("aspectY",son1);
                bgcamera.putExtra("outputX", 500);
                bgcamera.putExtra("outputY", 500);
                startActivityForResult(bgcamera, REQUEST_CROP);
                break;

            case REQUEST_CROP:
                fileList.add(temp_cmera.getPath());
                Glide.with(this)
                        .load(temp_cmera.getPath())
                        .asBitmap()
                        .into(new SimpleTarget<Bitmap>() {
                            @Override
                            public void onResourceReady(Bitmap resource, GlideAnimation<? super Bitmap> glideAnimation) {
                                Bitmap bitmap = null;
                                if (resource.getHeight() < 500) {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 1, resource.getHeight() / 1);
                                } else if (resource.getHeight() < 1000) {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 2, resource.getHeight() / 2);
                                } else {
                                    bitmap = Tools.zoomBitmap(resource, resource.getWidth() / 3, resource.getHeight() / 3);
                                }
                                try {
                                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, new FileOutputStream(temp_cmera));
                                    final View camera_imgview = View.inflate(MerchantFriendCircleSubmitActivity.this, R.layout.layout_uploadimg_layout, null);
                                    ImageView camera_imgview_iv = camera_imgview.findViewById(R.id.image);
                                    camera_imgview_iv.setImageBitmap(BitmapFactory.decodeFile(temp_cmera.getPath()));
                                    View camera_imgview__delte = camera_imgview.findViewById(R.id.delete_iv);
                                    final String t = temp_cmera.getPath();
                                    camera_imgview__delte.setOnClickListener(new View.OnClickListener() {
                                        @Override
                                        public void onClick(View view) {
                                            openuploadAll.removeView(camera_imgview);
                                            fileList.remove(t);
                                            File delete = new File(t);
                                            delete.delete();
                                        }
                                    });
                                    openuploadAll.addView(camera_imgview);
                                } catch (FileNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }
                        });

                break;

            case 106:
                String  datas = data.getStringExtra("data");
                if(datas==null){
                    return;
                }
                this.ars.add(datas);
                TextView textView = new TextView(this);
                textView.setText(""+datas);
                FlowLayout.LayoutParams lp = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
                lp.setMargins(5, 5, 5, 5);
                textView.setLayoutParams(lp);
                flowlayout.addView(textView);
                break;
        }

    }

    public void submit(String Text, String userFriendscircleTag, String userFriendscircleOfficialTag, String userFriendscircleType) {
        List<User> userList = Xutils.queryAll(getApplication(), User.class);
        if (userList == null || userList.size() == 0) {
            return;
        }
        User iser = userList.get(0);
        loadingdialog.show();
        RequestParams requestParams = new RequestParams(HttpUrl.usefriendcircleAdd);
        requestParams.addParameter("userId", iser.getUserId() + "");
        requestParams.addParameter("Text", Text);
        requestParams.addParameter("userCity", this.userCity);
        requestParams.addParameter("userArea", this.userArea);
        requestParams.addParameter("userAddress", this.userAddress);
        requestParams.addParameter("userLongitude", this.userLongitude + "");
        requestParams.addParameter("userLatitude", this.userLatitude + "");
        requestParams.addParameter("userFriendscircleTag", userFriendscircleTag);
        requestParams.addParameter("userFriendscircleOfficialTag", userFriendscircleOfficialTag);
        requestParams.addParameter("userFriendscircleType", userFriendscircleType);
        if (this.fileList.size() != 0) {
            for (String file : fileList) {
                requestParams.addParameter("files", new File(file));
            }
        }
        requestParams.setCharset("UTF-8");
        requestParams.setMultipart(true);
        x.http().post(requestParams, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                loadingdialog.dismiss();
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    Toast.makeText(getApplicationContext(), jsonObject.getString("message"), Toast.LENGTH_SHORT).show();
                    switch (jsonObject.getInt("state")) {
                        case HttpCode.SUCCESS:
                            setResult(RESULT_OK);
                            finish();
                            break;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                loadingdialog.dismiss();
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });
    }
}
